<script setup>
import commonForm from '@/components/commonForm.vue';
import {
  addUserAysnc,
  updateUserInfoAsync
} from '@/api/userManagement';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  //用户id
  userInfo: {
    type: Object,
    default: {}
  }
})

const emit = defineEmits(['closeDialog', 'updateDialog'])

const handleClose = () => {
  emit('closeDialog')
}

const handleReset = () => {
  formRef.value.resetForm()
}

//保存/更新
const handleUpdate = () => {
  formRef.value.validForm(saveUserInfo)
}

const saveUserInfo = async () => {
  try {
    console.log('%c [  ]-41', 'font-size:13px; background:pink; color:#bf2c9f;', formData.value)
    const password = formData.value.password
    formData.value.password = password ? password : ''
    const params = {
      ...formData.value
    }

    isUpdate.value && (params.id = props.userInfo.id)

    const res = isUpdate.value ? await updateUserInfoAsync(params) : await addUserAysnc(params)
    if (res && res.code + '' === '200') {
      const tips = isUpdate.value ? '成功修改用户信息!' : '成功添加用户！'
      ElMessage.success(tips)
      emit('updateDialog')
    } else if (res && res.code + '' !== '200') {
      ElMessage.error(res.msg)
    }

  } catch (error) {
    console.log('%c [ error ]-42', 'font-size:13px; background:pink; color:#bf2c9f;', error)
  }

}


const title = computed(() => !isUpdate.value ? '添加用户' : '更新用户')

const dialogVisible = computed(() => props.visible)


//扁担配置项
const defaultOptionList = ref([
  {
    data: {
      label: '账号',
      prop: 'userName',
    },
    component: 'el-input',
    $attrs: {
      placeholder: '请输入用户账号'
    }

  },
  {
    data: {
      label: '密码',
      prop: 'password',
    },
    component: 'el-input',
    $attrs: {
      placeholder: `请输入用户密码`,
      type: 'password',
      'show-password': true
    }
  },
  {
    data: {
      label: '确认密码',
      prop: 'password2',
    },
    component: 'el-input',
    $attrs: {
      placeholder: `请输入再次输入用户密码`,
      type: 'password',
      'show-password': true
    }
  },
  {
    data: {
      label: '昵称',
      prop: 'nickName',
    },
    component: 'el-input',
    $attrs: {
      placeholder: `请输入用户昵称`
    }
  },
  {
    data: {
      label: '联系方式',
      prop: 'mobile',
    },
    component: 'el-input',
    $attrs: {
      placeholder: `请输入用户联系方式`
    }
  },
  {
    data: {
      label: '状态',
      prop: 'accountState',
    },
    component: 'CustomizeFormSelect',
    $attrs: {
      placeholder: '请选择账号状态',
      optionList: [
        {
          value: 0,
          label: '可用',
        },
        {
          value: 1,
          label: '冻结',
        }
      ]
    }

  },
  {
    data: {
      label: '序号',
      prop: 'orderRank',
    },
    component: 'el-input-number',
    $attrs: {
      placeholder: '请输入排序的序号',
      type: 'number',
      min: 1,
      max: 99999,
      step: 1,
      'step-strictly': true
    }
  },

])

const optionList = computed(() => {
  if (!isUpdate.value) {
    return defaultOptionList.value.map(item => {
      if (item.data.prop === 'userName') {
        item.$attrs.disabled = false
      }
      return item
    })
  } else {
    return defaultOptionList.value.map(item => {
      if (item.data.prop === 'userName') {
        item.$attrs.disabled = true
      }
      return item
    }).filter(item => item.data.prop !== 'password2')

  }
})

//表单回显数据
const optionData = computed(() => props.userInfo)

//表单校验规则
const defaultOptionRuleList = ref({
  userName: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) return callback(new Error('请输入用户账号！'))
        const reg = /^(?=.{2,16})((?=.*\d)| (?=.*[A-Za-z])).*$/
        if (!reg.test(value)) {
          callback(new Error('账号长度在2-16位且包含字母或数字!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      validator: (rule, value, callback) => {
        const reg = /^(?=.{6,16})(?=.*\d)(?=.*[A-Za-z]).*$/

        if (!isUpdate.value) {
          if (!value) return callback(new Error('请输入用户密码！'))
          if (!reg.test(value)) {
            callback(new Error('密码长度在6-16位且包含字母和数字!'))
          } else {
            callback()
          }
        } else {
          if (value && !reg.test(value)) {
            callback(new Error('密码长度在6-16位且包含字母和数字!'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  password2: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!formData.value.password) return callback(new Error('请先输入用户密码！'))
        if (!value) return callback(new Error('请再次输入用户密码！'))
        if (value !== formData.value.password) {
          callback(new Error('两次密码不一致！请重新输入'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  mobile: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) return callback(new Error('请输入用户联系方式'))
        const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
        if (!reg.test(value)) {
          callback(new Error('请输入正确的联系方式'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  accountState: [{ required: true, message: '请选择用户账号状态', trigger: 'blur' }],
  orderRank: [{ required: true, message: '请输入用户账号序号', trigger: 'blur' }],

})

const optionRuleList = computed(() => {
  if (!isUpdate.value) {
    return defaultOptionRuleList.value
  } else {
    const { userName, password2, ...otherRules } = defaultOptionRuleList.value
    console.log('%c [ otherRules ]-258', 'font-size:13px; background:pink; color:#bf2c9f;', otherRules)
    otherRules.password[0].required = false
    return otherRules
  }
})

//是更新用户？
const isUpdate = computed(() => Object.keys(props.userInfo).length)

const formRef = ref(null)
const formData = ref({})

const updateFormData = (data) => {
  formData.value = data
}



</script>

<template>
  <div class="dialog-container">
    <el-dialog v-model="dialogVisible" :title="title" width="500" :before-close="handleClose" align-center
      :close-on-click-modal="false" :close-on-press-escape="false" :center="true" :destroy-on-close="true">
      <el-card>
        <commonForm ref="formRef" :optionList="optionList" :optionRuleList="optionRuleList" :optionData="optionData"
          @updateFormData="updateFormData">
        </commonForm>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button class="btn-blue" type="primary" @click="handleReset">
            重置
          </el-button>
          <el-button class="btn-green" type="primary" @click="handleUpdate">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-button) {
  color: #fff;
  width: 100px;
  height: 35px;
  font-size: 16px;
  border-color: #c6c6c6;
}
</style>